<template>
  <div class="page-container">
    <!-- 固定头部区域 -->
    <div class="page-header-fixed">
      <!-- 标题和操作按钮 -->
      <div class="page-title">
        <div class="title-left">
          <h2>{{ title }}</h2>
          <p v-if="description" class="title-desc">{{ description }}</p>
        </div>
        <div v-if="$slots.actions || actions.length > 0" class="action-bar">
          <slot name="actions">
            <a-space>
              <a-button
                v-for="action in actions"
                :key="action.key"
                :type="action.type || 'default'"
                :danger="action.danger"
                @click="action.onClick"
                v-permission="action.permission"
              >
                <template v-if="action.icon" #icon>
                  <component :is="action.icon" />
                </template>
                {{ action.label }}
              </a-button>
            </a-space>
          </slot>
        </div>
      </div>

      <!-- 筛选区域（支持展开/收起） -->
      <a-card v-if="$slots.filters || showFilters" class="filter-card">
        <div
          class="query-form"
          :style="{
            height:
              contentHeight === 0
                ? `${singleLineHeight}px`
                : defaultExpand
                ? `${contentHeight}px`
                : expanded
                ? `${contentHeight}px`
                : `${singleLineHeight}px`,
            overflow: 'hidden',
            transition: contentHeight === 0 ? 'none' : 'height 0.3s ease',
          }"
        >
          <div class="query-form-flex" ref="filterContentRef">
            <div class="query-form-content">
              <slot name="filters">
                <a-form :model="queryParams" :colon="false" class="filter-form">
                  <div
                    class="filter-grid"
                    :class="{ initialized: contentHeight > 0 }"
                  >
                    <slot name="filter-items"></slot>
                    <!-- 展开时的按钮 -->
                    <div
                      v-if="expanded || defaultExpand"
                      class="filter-actions-item"
                    >
                      <a-space>
                        <a-button type="primary" @click="handleSearch">
                          <template #icon><SearchOutlined /></template>
                          查询
                        </a-button>
                        <a-button @click="handleReset">
                          <template #icon><ReloadOutlined /></template>
                          重置
                        </a-button>
                        <a-button
                          v-if="hasMultipleLines && !defaultExpand"
                          type="link"
                          class="expand-btn"
                          @click="handleToggle"
                        >
                          收起
                          <DownOutlined class="icon-rotated" />
                        </a-button>
                      </a-space>
                    </div>
                  </div>
                </a-form>
              </slot>
            </div>
            <!-- 收起时的按钮 -->
            <template v-if="!expanded && !defaultExpand">
              <div class="query-form-actions">
                <a-space>
                  <a-button type="primary" @click="handleSearch">
                    <template #icon><SearchOutlined /></template>
                    查询
                  </a-button>
                  <a-button @click="handleReset">
                    <template #icon><ReloadOutlined /></template>
                    重置
                  </a-button>
                  <a-button
                    v-if="hasMultipleLines"
                    type="link"
                    class="expand-btn"
                    @click="handleToggle"
                  >
                    展开
                    <DownOutlined />
                  </a-button>
                </a-space>
              </div>
            </template>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 可滚动内容区 -->
    <div class="page-content">
      <div class="table-wrapper">
        <a-card class="table-card">
          <a-table
            :columns="columns"
            :data-source="dataSource"
            :loading="loading"
            :pagination="false"
            :scroll="computedTableScroll"
            :row-key="rowKey"
            v-bind="$attrs"
          >
            <template
              v-for="(_, name) in $slots"
              :key="name"
              #[name]="slotProps"
            >
              <slot :name="name" v-bind="slotProps || {}"></slot>
            </template>
          </a-table>
        </a-card>

        <!-- 分页器 -->
        <div v-if="showPagination" class="pagination-wrapper">
          <a-pagination
            v-model:current="paginationData.current"
            v-model:page-size="paginationData.pageSize"
            :total="paginationData.total"
            :show-size-changer="true"
            :show-quick-jumper="true"
            :show-total="(total: number) => `共 ${total} 条`"
            :page-size-options="
              paginationData.pageSizeOptions || ['10', '20', '50', '100']
            "
            @change="handlePaginationChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from "vue";
import {
  SearchOutlined,
  ReloadOutlined,
  DownOutlined,
} from "@ant-design/icons-vue";
import { useResizeObserver } from "@vueuse/core";
import type { TableColumnsType } from "ant-design-vue";

interface Action {
  key: string;
  label: string;
  type?: "primary" | "default" | "dashed" | "link" | "text";
  icon?: any;
  danger?: boolean;
  permission?: string;
  onClick: () => void;
}

interface PaginationData {
  current: number;
  pageSize: number;
  total: number;
  pageSizeOptions?: string[];
}

interface Props {
  // 标题相关
  title: string;
  description?: string;

  // 操作按钮
  actions?: Action[];

  // 筛选相关
  showFilters?: boolean;
  queryParams?: Record<string, any>;
  defaultExpand?: boolean; // 是否默认展开筛选区域

  // 表格相关
  columns: TableColumnsType;
  dataSource: any[];
  loading?: boolean;
  rowKey?: string | ((record: any) => string);
  tableScroll?: { x?: string | number; y?: string | number };

  // 分页相关
  showPagination?: boolean;
  paginationData?: PaginationData;
}

const props = withDefaults(defineProps<Props>(), {
  actions: () => [],
  showFilters: true,
  queryParams: () => ({}),
  defaultExpand: false,
  loading: false,
  rowKey: "id",
  tableScroll: () => ({ x: 1200 }), // 只设置横向滚动，纵向由flex布局控制
  showPagination: true,
  paginationData: () => ({
    current: 1,
    pageSize: 20,
    total: 0,
    pageSizeOptions: ["10", "20", "50", "100"],
  }),
});

const emit = defineEmits<{
  search: [];
  reset: [];
  paginationChange: [page: number, pageSize: number];
}>();

// 计算表格滚动配置 - 强制启用纵向滚动
// 设置一个很大的值，实际高度会被flex容器限制，但会启用滚动功能
const computedTableScroll = computed(() => ({
  ...props.tableScroll,
  y: "100%", // 设置一个足够大的值，让表格在flex容器中正确启用滚动
}));

// 筛选区域展开/收起相关
const filterContentRef = ref<HTMLElement>();
const expanded = ref(false);
const hasMultipleLines = ref(false);
const contentHeight = ref(0);
const singleLineHeight = 40; // 单行高度

// 切换展开/收起
const handleToggle = () => {
  expanded.value = !expanded.value;
  nextTick(() => {
    calculateFormItemRows();
  });
};

// 计算每个表单项所在的行数，并控制显示/隐藏
const calculateFormItemRows = () => {
  if (!filterContentRef.value) return;

  const container = filterContentRef.value;
  let rowCount = 0;

  // 查找所有表单项（不包括展开时的按钮项）
  const formItems = Array.from(
    container.querySelectorAll(".ant-form-item")
  ).filter((item: any) => {
    return (
      !item.classList.contains("filter-actions-item") &&
      !item.closest(".filter-actions-item")
    );
  });

  if (formItems.length === 0) {
    // 没有筛选项时，设置默认高度
    contentHeight.value = singleLineHeight;
    hasMultipleLines.value = false;
    return;
  }

  // 先重置所有样式，让内容自然布局
  formItems.forEach((item: any) => {
    item.style.visibility = "visible";
    item.style.height = "auto";
    item.style.overflow = "visible";
  });

  // 等待布局完成后计算
  nextTick(() => {
    // 计算每个表单项在第几行
    formItems.forEach((item: any, index: number) => {
      const itemOffset = item.offsetTop;
      if (index === 0 || itemOffset > (formItems[index - 1] as any).offsetTop) {
        rowCount++;
      }
      // 给每个元素添加行信息
      item.setAttribute("data-row", rowCount.toString());
    });

    // 获取实际内容高度
    contentHeight.value = container.offsetHeight;

    // 判断是否有多行
    hasMultipleLines.value = rowCount > 1;

    // 如果收起状态且有多行，隐藏非第一行的项
    if (!expanded.value && !props.defaultExpand && hasMultipleLines.value) {
      formItems.forEach((item: any) => {
        const row = item.getAttribute("data-row");
        if (row !== "1") {
          item.style.visibility = "hidden";
          item.style.height = "0";
          item.style.overflow = "hidden";
        }
      });
    }
  });
};

// 使用 VueUse 的 useResizeObserver 监听尺寸变化
useResizeObserver(filterContentRef, () => {
  calculateFormItemRows();
});

// 组件挂载后检测
onMounted(() => {
  setTimeout(() => {
    calculateFormItemRows();
  }, 100);
});

const handleSearch = () => {
  emit("search");
};

const handleReset = () => {
  emit("reset");
};

const handlePaginationChange = (page: number, pageSize: number) => {
  emit("paginationChange", page, pageSize);
};
</script>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0; /* 关键：允许flex子元素正确计算高度 */
  overflow: hidden;
}

/* 固定头部区域 */
.page-header-fixed {
  flex-shrink: 0;
  background: #fff;
  margin-bottom: 16px;
}

.page-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.title-left {
  flex: 1;
}

.page-title h2 {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 4px 0;
  line-height: 1.4;
}

.title-desc {
  font-size: 13px;
  color: var(--text-secondary);
  margin: 0;
  line-height: 1.5;
}

.action-bar {
  flex-shrink: 0;
  margin-left: 24px;
  margin-bottom: 0;
}

/* 筛选卡片 */
.filter-card {
  background: #fff;
  border: none;
  margin-bottom: 12px;
  box-shadow: none !important;
  transition: none !important;
}

.filter-card:hover {
  box-shadow: none !important;
  transform: none !important;
}

:deep(.filter-card .ant-card-body) {
  padding: 20px 0;
}

.query-form {
  position: relative;
}

.query-form-flex {
  display: flex;
  gap: 16px;
}

.query-form-content {
  flex: 1;
}

.filter-form {
  width: 100%;
}

.filter-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  /* 初始状态：限制最大高度为单行，防止内容撑高页面 */
  max-height: 50px;
  overflow: hidden;
}

/* 计算完成后移除高度限制 */
.filter-grid.initialized {
  max-height: none;
}

:deep(.filter-form .ant-form-item) {
  margin: 0 !important;
  transition: visibility 0.3s ease, height 0.3s ease;
  background-color: #f3f4f7;
  border-radius: 6px;
}

/* 支持自定义列跨度 */
:deep(.filter-form .ant-form-item.col-span-2) {
  grid-column: span 2;
}

:deep(.filter-form .ant-form-item.col-span-3) {
  grid-column: span 3;
}

:deep(.filter-form .ant-form-item.col-span-4) {
  grid-column: span 4;
}

/* 按钮项 - 不要背景和边框 */
:deep(.filter-form .filter-actions-item) {
  background: none !important;
  display: flex;
  align-items: center;
}

/* 表单项容器 */
:deep(.filter-form .ant-form-item .ant-form-item-row) {
  position: relative;
  padding-left: 8px;
  border: 1px solid #f3f4f7;
  border-radius: 6px;
  height: 32px;
  transition: all 0.3s ease;
}

/* hover 效果 */
:deep(.filter-form .ant-form-item .ant-form-item-row:hover) {
  border: 1px solid var(--primary-color);
  background: #ffffff;
}

/* focus 效果 */
:deep(.filter-form .ant-form-item .ant-form-item-row:focus-within) {
  background: #ffffff;
  border: 1px solid var(--primary-color);
  box-shadow: 0px 0px 3px 1px rgba(99, 102, 241, 0.3);
}

/* label 样式 */
:deep(.filter-form .ant-form-item label.ant-form-item-no-colon) {
  font-size: 12px !important;
  font-weight: 400;
  color: #9097a7;
}

/* 输入框透明背景 */
:deep(.filter-form .ant-form-item .ant-input) {
  background: none !important;
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
  font-size: 12px !important;
}

/* 去掉自动填充的背景色 */
:deep(.filter-form .ant-form-item .ant-input:-webkit-autofill) {
  -webkit-transition-delay: 99999s;
  -webkit-transition: color 99999s ease-out, background-color 99999s ease-out;
}

/* 输入框包装器 */
:deep(.filter-form .ant-form-item .ant-input-affix-wrapper) {
  background: none !important;
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
  font-size: 12px !important;
}

/* 选择框 */
:deep(.filter-form .ant-form-item .ant-select .ant-select-selector) {
  background: none !important;
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
  font-size: 12px !important;
}

/* 日期选择器 */
:deep(.filter-form .ant-form-item .ant-picker) {
  background: none !important;
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
  font-size: 12px !important;
  width: 100% !important;
}

/* 输入框、选择框占满宽度 */
:deep(.filter-form .ant-form-item .ant-input),
:deep(.filter-form .ant-form-item .ant-select),
:deep(.filter-form .ant-form-item .ant-picker) {
  width: 100% !important;
}

/* 收起时的按钮区域 */
.query-form-actions {
  flex-shrink: 0;
  display: flex;
  align-items: flex-start;
  min-width: 210px;
}

.expand-btn {
  padding: 4px 8px;
  color: var(--primary-color);
}

.expand-btn :deep(.anticon) {
  margin-left: 4px;
  transition: transform 0.3s ease;
  font-size: 12px;
}

.expand-btn :deep(.icon-rotated) {
  transform: rotate(180deg);
}

/* 可滚动内容区 */
.page-content {
  /* flex: 1; */
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 0;
}

.table-card {
  flex: 1; /* 填充父容器高度 */
  display: flex;
  flex-direction: column;
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-sm);
  min-height: 0;
  overflow: hidden;
}

:deep(.table-card .ant-card-body) {
  padding: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

:deep(.ant-table-wrapper) {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

:deep(.ant-spin-nested-loading),
:deep(.ant-spin-container) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.ant-table) {
  border-radius: var(--radius-lg);
  flex: 1;
  display: flex; /* 设置为flex容器 */
  flex-direction: column; /* 子元素垂直排列 */
  min-height: 0; /* 允许正确计算flex高度 */
}

:deep(.ant-table-container) {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

:deep(.ant-table-header) {
  flex-shrink: 0;
  overflow: hidden !important;
  width: 100% !important;
}

/* 表格内容区域（包含表头和表体） */
:deep(.ant-table-content) {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

:deep(.ant-table-body) {
  flex: 1;
  overflow-y: auto !important;
  overflow-x: auto !important;
  /* 预留滚动条空间，防止滚动条出现/消失导致高度变化 */
  scrollbar-gutter: stable;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
  color: var(--text-primary);
  padding: 12px 16px;
  border-bottom: 1px solid var(--border-color);
}

:deep(.ant-table-tbody > tr > td) {
  padding: 12px 16px;
  font-size: 13px;
  border-bottom: 1px solid var(--border-color-light);
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f0f9ff !important;
}

/* 分页器 */
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 12px 0;
}

:deep(.ant-pagination) {
  margin: 0;
}
:deep(.ant-input, .ant-input-affix-wrapper) {
  border-radius: 0 !important;
}
</style>
